// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
// 获取答题详情
exports.main = async (event, context) => {
  const db = cloud.database()
  const wxContext = cloud.getWXContext()
  const { test_id, openid } = event
  // 处理没有文件的情况
  let file = [{}]

  const titles = await db.collection('title').where({ test_id, openid }).get()
  const test = await db.collection('test').doc(test_id).get()
  const testRecords = await db.collection('test-record').where({ openid, test_id }).get()
  if (test.data.has_file) {
    let fileResult = await db.collection('file').where({ openid, test_id }).get()
    file = fileResult.data
  }

  return {
    title: titles.data,
    test: test.data,
    file,
    record: testRecords.data
  }
}